<?php

namespace core;
/**
 * 视图类
 * 视图->模板->有数据占位符的字符串
 * 模板入口：app/admin/view
 * 模板文件：controller/action.html
 */
require __DIR__.'common.php';
class View
{
    //模版入口路径
    protected string $defaultPath;
    //当前控制器
    protected string $controller;
    //当前方法
    protected string $action;

    //模板变量容器
    protected array $data = [];
    //构造器
    public function __construct(string $defaultPath, string $controller, string $action)
    {
        $this->defaultPath = $defaultPath;
        $this->controller = $controller;
        $this->action = $action;
    }

    //1.模板赋值
    public function assign($key,$value = null)
    {
        if (is_array($key)){
            $this->data = array_merge($this->data,$key);
        }else{
            $this->data[$key] = $value;
        }
    }
    //2.渲染模板:允许渲染的时候，同步实现模板的赋值
    public function render(string $path = null, array $data = [])
    {
        $this->data = $data ? array_merge($this->data,$data) : $this->data;
        //因为方法之间的作用域是隔离的，所以需要展开
        extract($this->data);
        $file = $this->defaultPath.$this->controller.'/'.$this->action.'.html';
        file_exists($file) ? include ($file) : die("模板文件不存在");
    }
}
